<!-- 授权弹窗页面 -->
<template>
  <n-modal
    v-model:show="showModal"
    preset="dialog"
    :show-icon="false"
    :auto-focus="false"
    title="Dialog"
    :mask-closable="false"
    :closable="false"
    style="width: 70%"
  >
    <template #header>
      <n-space justify="space-between" class="head-row">
        <div>{{ modalTitle }}</div>
        <n-button @click="handlePageClose" size="small">关闭</n-button>
      </n-space>
    </template>
    <n-grid x-gap="20" :cols="5">
      <n-grid-item :span="2">
        <n-card class="tree-card">
          <n-space justify="end">
            <n-button type="error" size="small" class="save-btn" @click="handleTreeSave">保 存</n-button>
          </n-space>
          <n-tree
            show-line
            block-line
            default-expand-all
            virtual-scroll
            style="height: 600px"
            :data="treeData"
            expand-on-click
            checkable
            key-field="key"
            label-field="label"
            children-field="children"
          />
        </n-card>
      </n-grid-item>
      <n-grid-item :span="3">
        <n-space vertical>
          <n-card>
            <n-space vertical>
              <n-space justify="space-between">
                <n-space align="center">
                  姓名
                  <n-input v-model:value="listQurey.name" placeholder="请输入姓名" />
                </n-space>
                <n-button type="error" size="small" class="save-btn" @click="handleTableSave">保 存</n-button>
              </n-space>
              <n-data-table
                :bordered="false"
                :single-line="false"
                :row-key="rowKey"
                :columns="columns"
                @update:checked-row-keys="handleCheck"
                :data="tableData"
                :loading="listLoading"
              />
              <n-space>
                <n-pagination :item-count="tableTotal" :page-sizes="[10, 20, 30, 40]" show-size-picker>
                  <template #prefix="{ itemCount }">共 {{ itemCount }} 条</template>
                </n-pagination>
              </n-space>
            </n-space>
          </n-card>
          <n-space>已勾选：</n-space>
          <n-space>
            <n-tag type="info" closable @close="handleTagClose(t, i)" v-for="(t, i) in checkedRowKeysRef" :key="i">{{ t.name }}</n-tag>
          </n-space>
        </n-space>
      </n-grid-item>
    </n-grid>
  </n-modal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { repeat } from 'seemly'
  import { NGrid, NGridItem, NCard, NTree, NSpace, NButton, NInput, NDataTable, NPagination, NModal, NTag, useDialog } from 'naive-ui'
  import type { TreeOption, DataTableColumns, DataTableRowKey } from 'naive-ui'
  const emit = defineEmits(['cancelModal'])

  const showModal = ref(true)
  const modalTitle = ref('授权')
  const listLoading = ref(false)
  const listQurey = ref({ name: null })
  const tableData = ref([])
  const rowKey = ref((row: RowData) => JSON.stringify(row))
  const checkedRowKeysRef = ref([] as any)

  const fatherElement = defineProps({
    // 接收传值   此处的father就是父组件的自定义名称
    father: {
      type: String, // 数据类型
      default: '' // 未传值时的默认值
    }
  })

  function createTreeData(level = 4, baseKey = ''): TreeOption[] | undefined {
    if (!level) return undefined
    return repeat(5 - level, undefined).map((_, index) => {
      const key = `${baseKey}${level}${index}`
      return {
        label: createLabel(level),
        key: key,
        children: createTreeData(level - 1, key)
      }
    })
  }

  function createLabel(level: number): string {
    if (level === 4) return '菜单'
    if (level === 3) return '一生二'
    if (level === 2) return '二生三'
    if (level === 1) return '三生万物'
    return ''
  }

  const treeData = createTreeData()
  console.log('data', treeData)

  // 表格选中
  function handleCheck(rowKeys: DataTableRowKey[]) {
    if (rowKeys.length > 0) {
      checkedRowKeysRef.value = rowKeys.map((m: any) => {
        return JSON.parse(m) as any
      }) as any
    } else {
      checkedRowKeysRef.value = []
    }
  }
  // 关闭tag
  function handleTagClose(item: any, index: number) {
    checkedRowKeysRef.value.splice(index, 1)
  }
  function handleTreeSave() {}
  function handleTableSave() {}
  // 授权弹窗关闭
  const dialog = useDialog()
  function handlePageClose() {
    dialog.warning({
      title: '警告',
      content: '请分别保存后，再关闭，你确定已保存？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        emit('cancelModal', false)
      },
      onNegativeClick: () => {}
    })
  }
  // 获取表格数据
  search()
  function search() {
    listLoading.value = true
    tableData.value = createTableData() as any
    setTimeout(() => {
      listLoading.value = false
    }, 1000)
  }

  interface RowData {
    no: number
    name: string
    loginName: string
    icon: string
    gender: number
    status: number
  }
  function createTableData(): RowData[] {
    return [
      {
        no: 0,
        name: 'John Brown',
        loginName: '32',
        icon: '',
        gender: 0,
        status: 1
      },
      {
        no: 1,
        name: 'Jim Green',
        loginName: '42',
        icon: '',
        gender: 1,
        status: 0
      },
      {
        no: 2,
        name: 'Joe Black',
        loginName: '32',
        icon: '',
        gender: 0,
        status: 1
      }
    ]
  }

  function createColumns(): DataTableColumns<RowData> {
    return [
      {
        type: 'selection'
      },
      {
        title: '姓名',
        key: 'name'
      },
      {
        title: '登录名称',
        key: 'loginName'
      },
      {
        title: '性别',
        key: 'gender'
      },
      {
        title: '状态',
        key: 'status',
        render(row) {
          return row.status === 1 ? '启用' : '停用'
        }
      }
    ]
  }
  const columns = createColumns()
  const tableTotal = tableData.value.length
</script>
<style lang="less" scoped>
  .head-row {
    width: 100%;
    margin-bottom: 20px;
  }
  .save-btn {
    margin-bottom: 20px;
  }
</style>
